import {message, Tabs, Divider, DatePicker} from 'antd'
import React, { useState, useRef} from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import { queryResignationList, updateDimissionSettlement, dimissionSettlementBpm, updateDimissionSettlementStatus, deleteDimissionSettlement } from './service'
import CreateForm from './components/CreateForm'
import CreateReasonForm from './components/CreateReasonForm'
import moment from 'moment';
import { modeList, dimissionTypeList,  BPMStatusEnum } from '@/utils/constant'

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const TableList = (props) => {
  const { personnel = {}, currentUser } = props;
  const {options = {}} = personnel;
  const { jobLevel = [] } = options;
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [done, setDone] = useState(false);
  const [visible, setVisible] = useState(false);
  const [reasonVisible, setReasonVisible] = useState(false);
  const [current, setCurrent] = useState(undefined);
  const { authorities } = currentUser;
  const canDelete = authorities.indexOf("user:info:editall") > -1;
  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width:60,
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
      hideInSearch: true,

    },
    {
      title: '职级',
      dataIndex: 'jobLevelId',
      hideInSearch: true,
      render: (text) =>{
        return text!=='-' ? jobLevel.find(item => item.id===text)?.name : '';
      }
    },
    {
      title: '公司名称',
      dataIndex: 'orgname',
      hideInSearch: true,
    },
    {
      title: '部门名称',
      dataIndex: 'unitname',
      hideInSearch: true,
    },
    {
      title: '入职日期',
      dataIndex: 'hiredate',
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
      renderFormItem: (item, props) => {
        return <RangePicker {...props} />;
      },
    },
    {
      title: '离职日期',
      dataIndex: 'dimissionTime',
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
      hideInSearch: true,
    },
    {
      title: '司龄',
      dataIndex: 'workingYears',
      hideInSearch: true,
    },
    {
      title: '离职方式',
      dataIndex: 'mode',
      hideInSearch: true,
      render: (text, record) => {
        const res = modeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '离职类型',
      dataIndex: 'dimissionType',
      hideInSearch: true,
      render: (text, record) => {
        const res = dimissionTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: BPMStatusEnum
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {record.status===0 && <>
            <a onClick={() => saveSettlement(record)}>编辑</a>
            <Divider type="vertical"/>
            <a onClick={() => settlement(record.id)}>结算</a>
          </>
          }
          {record.bpmDetailUrl && record.status!==0 && <a onClick={() => window.open(record.bpmDetailUrl)}>审批详情</a>}
          {(record.status===2 && record.processingStatus !== 2) && <>
              <Divider type="vertical"/>
            <a onClick={() => confirmSettlement(record)}>确认</a>
          </>}
          {canDelete && <>
            <Divider type="vertical"/>
            <a onClick={() => deleteSettlement(record)}>删除</a>
          </>}
        </>
      ),
    },
  ];

  const handleChangTabIndex = (key) => {
    if(key === '0'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const saveSettlement = (record) =>{
    setVisible(true);
    record.dimissionTime = record.dimissionTime?moment(record.dimissionTime):null;
    record.hiredate = record.hiredate?moment(record.hiredate):null;
    setCurrent(record);
  };

  const settlement = (id) => {
    dimissionSettlementBpm(id).then(res => {
      if (res.flag){
        window.open(res.data)
      }else {
        message.error(res.error)
      }
      actionRef.current.reload()
    })
  };

  const confirmSettlement = (record) =>{
    setCurrent(record);
    setReasonVisible(true);
  }

  const deleteSettlement = (record) =>{
    deleteDimissionSettlement(record.id).then(res => {
      if (res.flag){
        message.success('删除成功！');
        actionRef.current.reload();
      }else {
        message.error(res.error)
      }
    })
  }

  const handleCancel = () => {
    setCurrent(null);
    setVisible(false)
  };

  const reasonHandleCancel = () =>{
    setCurrent(null);
    setReasonVisible(false);
  };

  const reasonHandleSubmit = (values) => {
    updateDimissionSettlementStatus(values).then(res => {
      if (res.flag){
        message.success('离职结算确认成功');
      }else {
        message.error(res.error);
      }
      setReasonVisible(false);
      actionRef.current.reload()
    })
  };

  const handleSubmit = (values) => {
    updateDimissionSettlement(values).then((res)=>{
      setDone(false);
      // setCurrent(null);
      setVisible(false);
      if (res.flag){
        message.success('离职结算信息保存成功！');
      }else {
        message.error(res.error);
      }
      actionRef.current.reload()
    })
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryResignationList(params,1)}
            columns={columns}
          />
        </TabPane>
        <TabPane tab="已办理" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => queryResignationList(params,2)}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <CreateForm
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <CreateReasonForm
        current={current}
        visible={reasonVisible}
        onCancel={reasonHandleCancel}
        onSubmit={reasonHandleSubmit}
      />
    </PageHeaderWrapper>
  )
}

export default connect(({ personnel, user }) => ({
  personnel,
  currentUser: user.currentUser,
}))(TableList)
